package com.caipiao.crawler.pailie;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.caipiao.constant.CrawlerConstants;
import com.caipiao.crawler.model.DaletouResultModel;
import com.caipiao.crawler.model.LotteryNumber;
import com.caipiao.crawler.model.PailiesanResultModel;
import com.caipiao.crawler.model.PailiewuResultModel;
import com.caipiao.crawler.page.BasePageProcessor;
import us.codecraft.webmagic.Page;

/**
 * Created by adminitrator on 2018/7/28.
 */
public class PailieResultPage extends BasePageProcessor {

    @Override
    public void process(Page page) {
        String url = page.getUrl().toString();
//        page.setUrl();
        System.out.println(url);
        if(url.contains("history")) {
            //历史页面,获取id
            processHistory(page);
        } else {
            //处理接口数据
            processData(page);
        }
    }

    public void processData(Page page) {
        String data = page.getJson().get();
        JSONObject obj = (JSONObject) ((JSONArray) JSON.parse(data)).get(0);
        JSONObject lottery = obj.getJSONObject("lottery");
        String plsNum = obj.getString("codeNumber");
        String plwNum = obj.getString("codeNumberPlw");
        plsNum = plsNum.substring(1,plsNum.length()-1).replaceAll("\"","").replaceAll(","," ");
        plwNum = plwNum.substring(1,plwNum.length()-1).replaceAll("\"","").replaceAll(","," ");
        LotteryNumber model3 = new LotteryNumber();
        LotteryNumber model5 = new LotteryNumber();
        model3.setType(2);
        model3.setPrize_detail(obj.getString("details"));
        model3.setDate(lottery.getString("openTime_fmt1"));
        model3.setCreated_time((int) (System.currentTimeMillis()/1000L));
        model3.setTerm(lottery.getString("term"));
        model3.setNumber(plsNum);
        model3.setTotal_sales(lottery.getString("totalSales"));
        page.putField("model3", model3);
        model5.setType(3);
        model5.setPrize_detail(obj.getString("detailsPlw"));
        model5.setDate(lottery.getString("openTime_fmt1"));
        model5.setCreated_time((int) (System.currentTimeMillis()/1000L));
        model5.setTerm(lottery.getString("term"));
        model5.setNumber(plwNum);
        page.putField("model5", model5);
    }

    public void processHistory(Page page) {
        page.setSkip(true);  //不需要传到pipeline
        String id = page.getHtml().xpath("//div[@class='result']/table/tbody/tr/td[1]/text()").toString();
        if(id == null) {
            //TODO error 日志
            return;
        }
        String targetUrl = CrawlerConstants.PAILIE_DATA_URL + id;
        page.addTargetRequest(targetUrl);
    }
}
